import React, { useRef,useEffect ,useState,forwardRef,useImperativeHandle} from 'react'
import { withRouter } from 'react-router-dom'
import MyTable from '@/components/common/table'
import Role from '@/api/role'
import Menu from '@/api/menu'
import $axios from '@/utils/axios'
import {  getQuery } from '@/assets/js/publicFunc'
import { Button,Modal,Form,Spin,Result,Input, Select, InputNumber} from 'antd'
import { modalLayoutSm } from '@/config/layout'
import getFtypeObj from '@/config/ftypes'
import moment from 'moment';
import MySelect from '@/components/common/mySelect'
import './index.less';
import ChoosArea from '@/components/common/choosearea'
const Commonlist = () => {
  const tableRef: RefType = useRef()
  const rowEdit: RefType = useRef()
  const query = getQuery()
  const { type } = query
  const fTypeObj = getFtypeObj(type);
  const operation_id = fTypeObj['operation_id'];
  
  const [isError,setIsError] = useState(false);
  const columns = [
    {
      key:'regionCode',
      dataIndex:'regionCode',
      title: '区域代码',
    },
    {
      key:'regionName',
      dataIndex:'regionName',
      title: '区域名称',
    },
    {
      key:'regionNameAbb',
      dataIndex:'regionNameAbb',
      title: '区域简称',
    },
    {
      key:'regionType',
      dataIndex:'regionType',
      title: '类别',
      render:(txt)=>{
        let regionTypeObj = {
          'province':'省',
          'city':'市',
          'county':'区'
        }
        return regionTypeObj[txt];
      }
    },
    {
      key:'levels',
      dataIndex:'levels',
      title: '层级',
      width:40,
    },
    {
      key:'parentRegionName',
      dataIndex:'parentRegionName',
      title: '上级区域',
    },
    {
      key:'loadDate',
      dataIndex:'loadDate',
      title: '修改时间',
      fotmat:'YYYY-MM-DD HH:mm',
      render:(txt,record)=>{
        return txt?moment(txt).format('YYYY-MM-DD HH:mm'):''
      }
    },
    {
      type:'operation',
      key:'operation',
      dataIndex:'updateTime',
      title: '操作',
      render:(txt,record)=>{
        return <div>
        <Button className="btn" onClick={()=>edit(record['regionCode'])} size="small">编辑</Button>
        <Button className="btn" style={{marginLeft:'10px'}} onClick={()=>del(record['regionCode'])} size="small">删除</Button>
      
      </div>
      }
    },
  ];
  // 添加
  const add = () => {
    rowEdit.current.init('');
  }
   // 修改
   const edit = (id) => {
    rowEdit.current.init(id);
  }
  // 删除
  const del = (id) => {
    Modal.confirm({
      title: '确认删除？',
      
      onOk() {
        let params:object = {
          
        }
        let list = [id];
        params['ids'] = list;
        $axios.post('/dm/api/baseinfo/region/delete',params).then(()=>{
          tableRef.current.update();
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  const getList = (params)=>{
     return $axios.post('/dm/api/baseinfo/region/list', params)
  }
  // 搜索栏配置项
  const searchConfigList = [
    {
      key: 'keyword',
      slot: <Input placeholder="请输入关键字" allowClear />,
      rules: [],
      initialValue: ''
    },
  ]
  return (
      <>
        <Button className="fr" onClick={add} style={{marginBottom:'15px'}} type="primary">
          新增
        </Button>
        <MyTable
          apiFun={getList}
          columns={columns}
          ref={tableRef}
          searchConfigList={searchConfigList}
          extraProps={{ results: 10 }}
        />
        <CommonEditCom ref={rowEdit} callback={()=>{
          tableRef.current.update();
        }}/>
      </>
      
  )
}

//新建/修改
const CommonEdit = (props,refs) => {
  const [loading, setLoading] = useState<boolean>(false)
  //显示隐藏弹窗
  const [isModalVisible, setIsModalVisible] = useState(false);
   //显示隐藏树
   const [isTreeVisible, setIsTreeVisible] = useState(false);
   //默认选中
   const [defauleChecked,setdDefaultCheck] = useState([]);
  //橘色is
  const [roleId,setId] = useState('');
  //form
  const [form] = Form.useForm()
  const { setFieldsValue, resetFields } = form
  //菜单树
  const [treeData,setTreeData] = useState<any[]>([]);
  const query = getQuery()
  const { type } = query
  const fTypeObj = getFtypeObj(type);
  const operation_id = fTypeObj['operation_id'];
  const ChooseAreaRef: RefType = useRef()

  const [parentRegionName,setparentRegionName] = useState('');
  useImperativeHandle(refs, () => ({
    init: (id) => {
      setId(id);
      if(id){
        getDetail(id);
      }else{
        resetFields();
        showModal();
        setdDefaultCheck([]);
        setIsTreeVisible(true)
      }
     
    }
  }))
  //获取详情
  const getDetail = (id)=>{
    let params:object = {
      'id':id
    }
    $axios.get('/dm/api/baseinfo/region/info', params).then((res)=>{
      setFieldsValue({
        regionCode:res['data']['regionCode'],
        regionName:res['data']['regionName'],
        regionNameAbb:res['data']['regionNameAbb'],
        regionType:res['data']['regionType'],
        parentRegionCode:res['data']['parentRegionCode'],
      });
      setparentRegionName(res['data']['parentRegionName']);
      setIsTreeVisible(true)
      showModal();
    })
  }
  //显示弹窗  
  const showModal = () => {
    setIsModalVisible(true);
  };
  //确定
  const handleOk = () => {
    form.validateFields().then((vals) => {
      const Obj = form.getFieldsValue()
      setLoading(true)

      const url = roleId===''?'/dm/api/baseinfo/region/add':'/dm/api/baseinfo/region/update';
      let regionTypeObj = {
        'province':1,
        'city':2,
        'county':3
      }
      const params = {
        ...Obj,
        ...{
          'levels':regionTypeObj[Obj['regionType']],
          
          status:1
        }
      };
      let fn = $axios.post;
      if(roleId){
        params['id'] = roleId;
        fn = $axios.put;
      }
      fn(url, params).then((res)=>{
        handleCancel();
      })
    }).catch(info => {
      
    })
  };
  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setId('');
    setparentRegionName('');
    setLoading(false);
    setIsTreeVisible(false);
    resetFields();
    props.callback&&props.callback();
  };
  const handleSubmit = () => {
    
    setTimeout(() => {
      setLoading(false)
      
    }, 1000)
  }
  const onSelect = (selectedKeys: React.Key[], info: any) => {
    console.log('selected', selectedKeys, info);
  };

  const onCheck = (checkedKeys, info: any) => {
    console.log('onCheck', checkedKeys, info);
    setFieldsValue({
      menuids:checkedKeys
    });
  }; 
  const setnowCheckedGroup = (OBJ)=>{
    setFieldsValue({
      parentRegionCode:OBJ['id'],
    })
    setparentRegionName(OBJ['name']);
  }
  return <Modal 
    title="区域设置" 
    visible={isModalVisible} 
    onOk={handleOk} 
    onCancel={handleCancel}
    width={600}
    destroyOnClose={true}
    maskClosable={false}
    >

    <Spin spinning={loading}>
      <Form {...modalLayoutSm} form={form} onFinish={handleSubmit}>
        <Form.Item
          label="区域代码"
          name="regionCode"
          rules={[
            {
              required: true,
              message: '请输入区域代码'
            },
            {
              len:6,
              message:'请输入6位区域代码'
            }
          ]}
        >
          <Input style={{width:'100%'}} placeholder="请输入区域代码" />
        </Form.Item>
        <Form.Item
          label="区域名称"
          name="regionName"
          rules={[
            {
              required: true,
              message: '请输入区域名称'
            }
          ]}
        >
          <Input placeholder="请输入区域名称" />
        </Form.Item>
        <Form.Item
          label="区域简称"
          name="regionNameAbb"
          rules={[
            {
              required: true,
              message: '请输入区域简称'
            }
          ]}
        >
          <Input placeholder="请输入区域简称" />
        </Form.Item>
        <Form.Item
          label="类别"
          name="regionType"
          rules={[
            {
              required: true,
              message: '请选择类别'
            }
          ]}
        > 
          <MySelect
            data={[
              { name:'省',key:'province',},
              { name:'市',key:'city',},
              { name:'区',key:'county',}
            ]}
          />
        </Form.Item>
        {/* <Form.Item
          label="层级"
          name="levels"
          rules={[
            {
              required: true,
              message: '请选择层级'
            }
          ]}
        > 
          <MySelect
            data={[
              { name:'1',key:'1',},
              { name:'2',key:'2',},
              { name:'3',key:'3'}
            ]}
          />
        </Form.Item> */}
         <Form.Item
          name="parentRegionCode"
          label="上级区域"
        >
           <div className="" onClick={()=>{
            ChooseAreaRef.current.init();
          }}>
             <Input value={parentRegionName}/>
          </div>
        </Form.Item>
      </Form>
    </Spin>
    <ChoosArea ref={ChooseAreaRef} callback={(callback_v)=>{
      let obj = callback_v[0];
      setnowCheckedGroup(obj)
    }}/>
</Modal>
}

const CommonEditCom = forwardRef(CommonEdit);
export default withRouter(Commonlist)
